# # 错误代码
# file=open("1.txt","r")
# # 出错的地方，导致文件没有关闭
# file.write("hello")
# file.close()

# 可以使用try...catch捕获异常
# try:
#     file = open("1.txt", "r")
#     file.write("hello")
# except Exception as e:
#     print("捕获异常")
# finally:
#     file.close()

# 用python的with方法,with可以自动调用和关闭文件操作，这种方式安全和简单
with open('1.txt',"r") as f:
    f.write("hello")